package com.pulaien.web.controller.common;


import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.pulaien.common.core.domain.AjaxResult;
import com.pulaien.common.domain.ResponseCode;
import com.pulaien.common.utils.ConstantsUtil;
import com.pulaien.common.utils.StringUtils;
import com.pulaien.common.utils.oss.ConstantPropertiesUtil;
import com.pulaien.system.domain.dto.ExtDownloadFileDto;
import com.pulaien.system.domain.dto.ExtUploadFileDto;
import com.pulaien.system.domain.dto.OssCallbackResult;
import com.pulaien.system.domain.dto.OssPolicyResult;
import com.pulaien.system.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Oss对象存储管理Controller
 * @author huzhiming
 */
@Slf4j
@RestController
@Api(tags = "Oss管理", description = "Oss管理")
@RequestMapping("/aliyun/oss")
@CrossOrigin // 解决跨域
public class OssController {
    @Autowired
    private OssService ossService;


    @ApiOperation(value = "oss上传签名生成")
    @RequestMapping(value = "/policy", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult policy() {
        OssPolicyResult result = ossService.policy();
        return AjaxResult.success(result);
    }

    @ApiOperation(value = "oss上传成功回调")
    @RequestMapping(value = "/callback", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult callback(HttpServletRequest request) {
        OssCallbackResult ossCallbackResult = ossService.callback(request);
        return AjaxResult.success(ossCallbackResult);
    }

    @PostMapping("/upload")
    @ApiOperation(value = "oss上传文件")
    public AjaxResult uploadFile(@Valid ExtUploadFileDto uploadFile) {
//        if (uploadFile.getFile() != null) {
//            return AjaxResult.error(ResultCode.FILE_IS_NOT_NULL);
//        }

        // 地域节点
        String endpoint = ConstantPropertiesUtil.ENDPOINT;
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = ConstantPropertiesUtil.KEYID;
        String accessKeySecret = ConstantPropertiesUtil.KEYSECRET;
        // BucketName
        String yourBucketName = ConstantPropertiesUtil.BUCKETNAME;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        String modular = StringUtils.isEmpty(uploadFile.getModular())?"":uploadFile.getModular();
        try {
            // 1.获取上传文件 MultipartFile file
            // @RequestParam("file") file 与表单输入项的name值保持一致

            // 2.获取上传文件名称，获取上传文件输入流
            String fileName = uploadFile.getFile().getOriginalFilename();
            //文件后缀名 jpg  和 png
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            if (ConstantsUtil.PDF.equals(uploadFile.getType())) {
                if (!ConstantPropertiesUtil.PDF.equals(suffixName)) {
                    return AjaxResult.error(ResponseCode.FORMAT_DOES_NOT_CORRESPOND);
                }
            } else if (ConstantsUtil.JPG.equals(uploadFile.getType())) {
                if (!ConstantPropertiesUtil.JPG.equals(suffixName) && !ConstantPropertiesUtil.PNG.equals(suffixName) && !ConstantPropertiesUtil.JPEG.equals(suffixName)) {
                    return AjaxResult.error(ResponseCode.FORMAT_DOES_NOT_CORRESPOND);
                }
            } else if (ConstantsUtil.APK.equals(uploadFile.getType())) {
                if (!ConstantPropertiesUtil.APK.equals(suffixName)) {
                    return AjaxResult.error(ResponseCode.FORMAT_DOES_NOT_CORRESPOND);
                }
            }else if (ConstantsUtil.EXCEL.equals(uploadFile.getType())) {
                if (!ConstantPropertiesUtil.XLS.equals(suffixName)&&!ConstantPropertiesUtil.XLSX.equals(suffixName)) {
                    return AjaxResult.error(ResponseCode.FORMAT_DOES_NOT_CORRESPOND);
                }
            }else if(ConstantsUtil.MP4.equals(uploadFile.getType())) {
                if (!ConstantPropertiesUtil.MP4.equals(suffixName)&&!ConstantPropertiesUtil.MP4.equals(suffixName)) {
                    return AjaxResult.error(ResponseCode.FORMAT_DOES_NOT_CORRESPOND);
                }
            } else if(ConstantsUtil.AVI.equals(uploadFile.getType())) {
                if (!ConstantPropertiesUtil.AVI.equals(suffixName)&&!ConstantPropertiesUtil.AVI.equals(suffixName)) {
                    return AjaxResult.error(ResponseCode.FORMAT_DOES_NOT_CORRESPOND);
                }
            }


            // 在文件名称之前添加uuid值，保证文件名称不重复
//            String uuid = UUID.randomUUID().toString();
            //时间戳
            long timeStamp = System.currentTimeMillis();
            fileName = timeStamp + suffixName;

            // 获取当前日期 2020/01/03
            String filePath = new DateTime().toString("yyyyMMdd");
            //如果为pdf结尾
            if (ConstantPropertiesUtil.PDF.equals(suffixName)) {
                fileName = ConstantPropertiesUtil.PDFPREFIX + filePath + "/" + fileName;
            } else if (ConstantPropertiesUtil.JPG.equals(suffixName) || ConstantPropertiesUtil.PNG.equals(suffixName) || ConstantPropertiesUtil.JPEG.equals(suffixName)) {
                fileName = ConstantPropertiesUtil.PREFIX + filePath + "/"  + fileName;
            } else if (ConstantPropertiesUtil.APK.equals(suffixName)) {
                fileName = ConstantPropertiesUtil.APKPREFIX + filePath + "/" + fileName;
            } else if (ConstantPropertiesUtil.DOC.equals(suffixName)
                    || ConstantPropertiesUtil.DOCX.equals(suffixName)
                    || ConstantPropertiesUtil.XLS.equals(suffixName)
                    || ConstantPropertiesUtil.XLSX.equals(suffixName)
                    || ConstantPropertiesUtil.PPT.equals(suffixName)
                    || ConstantPropertiesUtil.PPTX.equals(suffixName)
                    || ConstantPropertiesUtil.TXT.equals(suffixName)
                    || ConstantPropertiesUtil.GIF.equals(suffixName)
                    || ConstantPropertiesUtil.AI.equals(suffixName)
                    || ConstantPropertiesUtil.MP4.equals(suffixName)
                    || ConstantPropertiesUtil.AVI.equals(suffixName)
            ) {
                fileName = ConstantPropertiesUtil.FILEPREFIX + filePath + "/" + fileName;
            } else {
                return AjaxResult.error(ResponseCode.FILE_FORMAT_ERROR);
            }

            // 获取上传文件输入流
            InputStream in = uploadFile.getFile().getInputStream();

            // 3.把上传文件存储到阿里云oss里面
            // 上传文件流
            // 第一个参数时BucketName，第二个参数是文件名称，第三个参数是输入流
            ossClient.putObject(yourBucketName, fileName, in);


            // 返回上传之后的oss存储路径
            String path = "http://" + yourBucketName + "." + endpoint + "/" + fileName;


            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", path);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", fileName);
            ajax.put("originalFilename", uploadFile.getFile().getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            log.error(ConstantsUtil.EXCEPTION_CONTEXT, e);
            return AjaxResult.error();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }

    }

    @RequestMapping(value = "download", method = RequestMethod.POST)
    @ApiOperation(value = "oss下载文件")
    public void downloadFile(@Valid ExtDownloadFileDto downloadFile, HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 地域节点
        String endpoint = ConstantPropertiesUtil.ENDPOINT;
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = ConstantPropertiesUtil.KEYID;
        String accessKeySecret = ConstantPropertiesUtil.KEYSECRET;
        // BucketName
        String yourBucketName = ConstantPropertiesUtil.BUCKETNAME;
        //通知浏览器以附件形式下载
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(downloadFile.getFileName().getBytes(), "ISO-8859-1"));

        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        String fileName = downloadFile.getFileUrl().split("http://" + yourBucketName + "." + endpoint + "/")[1];

        OSSObject ossObject = ossClient.getObject(yourBucketName, fileName);
        // 读取文件内容。
        try (BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent()); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());) {

            byte[] buffer = new byte[1024];
            int lenght = 0;
            while ((lenght = in.read(buffer)) != -1) {
                out.write(buffer, 0, lenght);
            }
        } catch (Exception e) {
            log.error(ConstantsUtil.EXCEPTION_CONTEXT, e);
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }

    }

    @RequestMapping(value = "delFile", method = RequestMethod.POST)
    @ApiOperation(value = "oss下载文件")
    public AjaxResult delFile(@Valid ExtDownloadFileDto downloadFile, HttpServletRequest request, HttpServletResponse response) {

        // 地域节点
        String endpoint = ConstantPropertiesUtil.ENDPOINT;
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = ConstantPropertiesUtil.KEYID;
        String accessKeySecret = ConstantPropertiesUtil.KEYSECRET;
        // BucketName
        String yourBucketName = ConstantPropertiesUtil.BUCKETNAME;

        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            String[] split = downloadFile.getFileUrl().split("\\.");

            if (split.length > 0) {
                String newName = "." + split[split.length - 1];

                //防止直接把整个文件删除
                if (ConstantPropertiesUtil.JPG.equals(newName) || ConstantPropertiesUtil.PNG.equals(newName)
                        || ConstantPropertiesUtil.JPEG.equals(newName) || ConstantPropertiesUtil.PDF.equals(newName) ||
                        ConstantPropertiesUtil.APK.equals(newName) || ConstantPropertiesUtil.DOC.equals(newName)
                        || ConstantPropertiesUtil.DOCX.equals(newName) || ConstantPropertiesUtil.XLS.equals(newName)
                        || ConstantPropertiesUtil.XLSX.equals(newName) || ConstantPropertiesUtil.PPT.equals(newName)
                        || ConstantPropertiesUtil.PPTX.equals(newName) || ConstantPropertiesUtil.GIF.equals(newName)
                        || ConstantPropertiesUtil.AI.equals(newName) || ConstantPropertiesUtil.TXT.equals(newName)) {
                    String fileName = downloadFile.getFileUrl().split("http://" + yourBucketName + "." + endpoint + "/")[1];
                    ossClient.deleteObject(yourBucketName, fileName);

                    return AjaxResult.success(ResponseCode.SUCCESS);
                }
                return AjaxResult.error(ResponseCode.FILE_ADDRESS_ERROR);

            } else {
                return AjaxResult.error(ResponseCode.FILE_ADDRESS_ERROR);
            }
        } catch (Exception e) {
            log.error(ConstantsUtil.EXCEPTION_CONTEXT, e);
            return AjaxResult.error();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
    }

}















